package com.example.concurrent.chapter16;

import javafx.scene.control.Tab;

/**
 * @author Create By Liuqz
 * @date 2018/11/26 14:41
 */
public class EatNoodleThread extends Thread {

    private final String name;

    //左手边的餐具
//    private final Tableware leftTool;

    //右手边的餐具
//    private final Tableware rightTool;


    private final TablewarePair tablewarePair;

    public EatNoodleThread(String name, TablewarePair tablewarePair) {
        this.name = name;
        this.tablewarePair = tablewarePair;
    }

    @Override
    public void run() {
        while (true) {
            this.eat();
        }
    }

    //吃面的过程(可能会进入死锁)
    /*private void eat() {
        synchronized (leftTool) {
            System.out.println(name + " take up " + leftTool + "(left)");
            synchronized (rightTool) {
                System.out.println(name + " take up " + rightTool + "(right)");
                System.out.println(name + " is eating now");
                System.out.println(name + " put down " + rightTool + "(right)");
            }
            System.out.println(name + " put down " + leftTool + "(left)");
        }
    }*/

    private void eat() {
        synchronized (tablewarePair) {
            System.out.println(name + " take up " + tablewarePair.getLeftTool() + "(left)");
            System.out.println(name + " take up " + tablewarePair.getRightTool() + "(right)");
            System.out.println(name + " is eating now.");
            System.out.println(name + " put down " + tablewarePair.getRightTool() + "(right)");
            System.out.println(name + " put down " + tablewarePair.getLeftTool() + "(left)");
        }
    }

    public static void main(String[] args) {
        //运行这段程序可能吃不了几个回合就会进入死锁状态

        Tableware fork = new Tableware("fork");
        Tableware knife = new Tableware("knife");

        TablewarePair tablewarePair1 = new TablewarePair(fork, knife);
        TablewarePair tablewarePair2 = new TablewarePair(fork, knife);

        new EatNoodleThread("A", tablewarePair1).start();
        new EatNoodleThread("B", tablewarePair2).start();
    }
}
